<script setup>
import { ref, reactive, onMounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ZegoExpressEngine } from "zego-express-engine-webrtc";
import { getZgUserToken } from "@/api/login";
import { message } from "ant-design-vue";
import moment from "moment";

onMounted(() => {
  checkAndSetDeviceZgVideo();
});

const router = useRouter();
const store = useStore();
const roomId = store.state.roomId;
const username = store.state.user;

const isPub = ref(false);
const cameras = reactive([]);
const deviceID = ref("");

let zg = null;
let streamID = "";
let localStream = null;

const subTitle = `roomId:${roomId}  username:${username} `;
const appId = 11478049;
const secret = `a601e7de5756c85ac6d8a4840804136a`;
const server = `wss://webliveroom11478049-api.imzego.com/ws`;

//发布
const handlePub = () => {
  if (!deviceID.value) {
    message.error("请选择设备!");
    return;
  }
  isPub.value = !isPub.value;
  pubVideo(
    roomId,
    username,
    appId,
    secret,
    server,
    deviceID.value,
    "none",
    "local"
  );
};
//断开
const handleClose = () => {
  isPub.value = !isPub.value;
  console.log(zg)
  if (zg) {
    zg.logoutRoom(roomId);
    // 根据本端 streamID 停止推流
    zg.stopPublishingStream(streamID);
    // localStream 是调用 createZegoStream 接口获取的 ZegoLocalStream 实例对象
    zg.destroyStream(localStream);
    zg = null;
    localStream = null;
  }
};
//返回
const handleBack = () => {
  handleClose();
  router.push({ name: "Home" });
};
const handleChange = (value) => {
  console.log(`selected ${value}`);
};
//发布视频
const pubVideo = async (
  roomId,
  userName,
  appId,
  secret,
  server,
  video,
  audio,
  localDivId
) => {
  zg = new ZegoExpressEngine(appId, server);
  const config = {
    logLevel: "warn",
  };
  zg.setLogConfig(config);
  zg.on(
    "roomStreamUpdate",
    async (roomID, updateType, streamList, extendedData) => {
      // 房间内其他用户音视频流变化的通知
      if (updateType == "ADD") {
        // 流新增，开始拉流
        // 此处演示拉取流新增的列表中第一条流的音视频
        const streamID = streamList[0].streamID;
        // streamList 中有对应流的 streamID
        const remoteStream = await zg.startPlayingStream(streamID);
        // 创建媒体流播放组件
        const remoteView = zg.createRemoteStreamView(remoteStream);
        remoteView.play("remote-video", { enableAutoplayDialog: true });
      } else if (updateType == "DELETE") {
        // 流删除，通过流删除列表 streamList 中每个流的 streamID 进行停止拉流。
        const streamID = streamList[0].streamID;
        zg.stopPlayingStream(streamID);
      }
    }
  );

  const userID = new Date().getTime().toString();
  const postData = {
    appId,
    userId: userID,
    secret,
  };
  const token = await getZgUserToken(postData);
  zg.loginRoom(roomId, token, { userID, userName }, { userUpdate: true }).then(
    async (result) => {
      if (result == true) {
        console.log("login success");
        let videoConfig = {
          camera: {
            audio: audio === "none" ? false : true,
            audioInput: audio,
            video: video === "none" ? false : true,
            videoInput: video,
            videoQuality: 2,
            width: 1920,
            height: 1080,
            frameRate: 20,
            bitrate: 800,
          },
        };
        console.log(
          "%c [ --------发布参数---------- ]",
          "font-size:13px; background:pink; color:#bf2c9f;",
          videoConfig
        );
        localStream = await zg.createStream(videoConfig);
        console.log(
          "%c [ --------localStream---------- ]",
          "font-size:13px; background:pink; color:#bf2c9f;",
          localStream,
          moment().format("YYYY-MM-DD HH:mm:ss:SSS")
        );
        // 创建媒体流播放组件对象，用于预览本地流
        const localView = zg.createLocalStreamView(localStream);
        // 将播放组件挂载到页面，"local-video" 为组件容器 <div> 元素的 id 。
        localView.play(localDivId, { objectFit: "fill" });

        // 开始推流，将自己的音视频流推送到 ZEGO 音视频云
        streamID = new Date().getTime().toString();
        zg.startPublishingStream(streamID, localStream);
        zg.on("publisherStateUpdate", async (result) => {
          console.log(
            "%c [ --------publishresult---------- ]",
            "font-size:13px; background:pink; color:#bf2c9f;",
            result["state"],
            moment().format("YYYY-MM-DD HH:mm:ss:SSS")
          );
        });
      }
    }
  );
};
//获取设备
const checkAndSetDeviceZgVideo = async () => {
  try {
    const zg = new ZegoExpressEngine(appId, server);
    const config = {
      logLevel: "disable",
    };
    zg.setLogConfig(config);
    await zg.checkSystemRequirements();
    zg.enumDevices().then((res) => {
      if (res.cameras.length > 0) {
        res.cameras.forEach((item) => {
          const new_item = {
            label: item.deviceName,
            value: item.deviceID,
            key: item.deviceID,
          };
          cameras.push(new_item);
        });
      }
    });
  } catch (error) {
    console.log(error);
  }
};
</script>

<template>
  <div class="con--warp">
    <div class="title">
      <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        title="发布"
        :sub-title="subTitle"
        @back="handleBack"
      />
    </div>

    <div class="device--wrap">
      <span>摄像头:</span>
      <a-select
        ref="select"
        v-model:value="deviceID"
        style="width: 300px"
        :options="cameras"
        @change="handleChange"
      ></a-select>
    </div>

    <div class="local" id="local"></div>
    <div class="btn--wrap">
      <a-space>
        <a-button type="primary" v-show="!isPub" @click="handlePub"
          >发布</a-button
        >
        <a-button type="primary" v-show="isPub" @click="handleClose"
          >断开</a-button
        >
      </a-space>
    </div>
  </div>
</template>

<style scoped lang="scss">
.con--warp {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  flex-direction: column;
  .title {
    position: absolute;
    left: 20px;
    top: 20px;
  }
  .device--wrap {
    width: 500px;
  }
  .local {
    margin: 15px 0;
  }
  .btn--wrap {
    width: 500px;
  }
}
</style>
